package com.info.zhiduoduo.pay.exceptionhandler;

import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.exception.RollbackException;
import com.info.zhiduoduo.common.exception.SmartException;

import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import java.io.PrintWriter;
import java.io.StringWriter;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(value = Exception.class)
	public SmartResult exceptionHandle(Exception e) throws Exception {
		SmartResult smartResult = new SmartResult();
		log.error("全局异常", e);
		if(e instanceof SmartException){
			return SmartResult.ofException((SmartException) e);
		}if (e instanceof MybatisPlusException) {
			//数据库报错
			smartResult.setStateMsg(StatusMsg.StatusMsg_103);
		} else if (e instanceof MultipartException || e instanceof FileUploadBase.FileSizeLimitExceededException) {
			//文件上传超过限制
			smartResult.setStateMsg(StatusMsg.StatusMsg_105);
		} else if (e instanceof RollbackException) {
			smartResult.setState(StatusMsg.StatusMsg_198.getState());
			smartResult.setMsg(e.getMessage());
		} else if (e instanceof MethodArgumentNotValidException) {
			FieldError fieldError = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError();
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			if (fieldError != null) {
				smartResult.setMsg(fieldError.getDefaultMessage());
			}
		} else {
			smartResult.setStateMsg(StatusMsg.StatusMsg_198);
		}
		smartResult.setSystemerrormsg(getExceptionDetail(e));
		return smartResult;
	}

	//4、
	public static String getExceptionDetail(Throwable e) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw, true);
		e.printStackTrace(pw);
		pw.flush();
		sw.flush();
		return sw.toString();
	}
}
